﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MovieDB.Models;

namespace YourProjectName.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class MoviesController : ControllerBase
    {
        private readonly MovieService _movieService;

        public MoviesController(MovieService movieService)
        {
            _movieService = movieService;
        }

        [HttpGet]
        public async Task<ActionResult<List<Movie>>> GetMovies()
        {
            var movies = await _movieService.GetAllMoviesAsync();
            return Ok(movies);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Movie>> GetMovie(int id)
        {
            var movie = await _movieService.GetMovieByIdAsync(id);
            if (movie == null) return NotFound();
            return Ok(movie);
        }

        [HttpPost]
        public async Task<ActionResult<Movie>> CreateMovie(MovieCreateDto dto)
        {
            var movie = await _movieService.AddMovieAsync(
                dto.Name, dto.ReleaseDate, dto.Duration,
                dto.Language, dto.Introduction, dto.Rating);
            return CreatedAtAction(nameof(GetMovie), new { id = movie.Id }, movie);
        }

        [HttpPut("{id}")]
        public async Task<ActionResult> UpdateMovie(int id, MovieUpdateDto dto)
        {
            var result = await _movieService.UpdateMovieAsync(id, dto.Name, dto.Rating, dto.Introduction);
            if (!result) return NotFound();
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteMovie(int id)
        {
            var result = await _movieService.DeleteMovieAsync(id);
            if (!result) return NotFound();
            return NoContent();
        }
    }

    // DTO 类
    public class MovieCreateDto
    {
        public string Name { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Duration { get; set; }
        public string Language { get; set; }
        public string Introduction { get; set; }
        public float Rating { get; set; }
    }

    public class MovieUpdateDto
    {
        public string? Name { get; set; }
        public float? Rating { get; set; }
        public string? Introduction { get; set; }
    }
}